<?php
require_once 'util/class.dbservice.php';

class NoteDao {
	
	 public function addNote($noteId, $userId, $type, $note, $pics,
	 		$tags, $src, $ip, $timestamp, $replyUserId=0,
	 		$replyNoteId=0, $favCount=0, $cmtCount=0) {
	 	try {
	 		$collection = $this->getCollection($noteId);
	 		if(!$collection)
	 			return Constants::$ID_DB_ERROR;
	 		
	 		
	 		$collection->insert(array('_id'=>$noteId, 'uid'=>$userId, 'tp'=>$type,
	 				'note'=>$note, 
	 				'pics'=>$pics,'tags'=>$tags, 'src'=>$src, 'ts'=>$timestamp,
	 				'ip'=>$ip, 'rlyNid'=>$replyNoteId, 'rlyUid'=>$replyUserId,
	 				'favNum'=>$favCount, 'cmNum'=>$cmtCount));
	 		return $noteId;
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "NoteDao.addNote error, reason=".$e);
	 		return Constants::$ID_DB_ERROR;
	 	}
	 }
	 
	 public function getNoteForRead($noteId) {
	 	try {
	 		$collection = $this->getCollection($noteId);
	 		if(!$collection)
	 			return null;
	 	
	 		return $collection->findOne(array('_id'=>$noteId), array('tp'=>0, 'src'=>0, 'ip'=>0));
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "NoteDao.getNote error, reason=".$e);
	 		return null;
	 	}
	 }
	 
	 public function updateCommentNum($noteId, $num) {
	 	try {
	 		$db=DBService::getDbById('note', $noteId);
	 		$collectionName = DBService::getCollectionNameById('note', $noteId);
	 		$result=$db->command(array('findAndModify'=>$collectionName,
	 				'query'=>array('_id'=>$noteId),
	 				'update'=>array('$inc'=>array('cmNum'=>$num)),
	 				'new'=>true,
	 				'fields'=>array('cmNum'=>1),
	 				'upsert'=>true
	 				));
	 		
	 		if($result==null || $result['ok']!=1)
	 			return Constants::$NUM_DB_ERROR;
	 		return $result['value']['cmNum'];
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "NoteDao.updateCommentNum error, reason=".$e);
	 		return Constants::$NUM_DB_ERROR;
	 	}
	 }
	 
	 public function updateFavoriteNum($noteId, $num) {
	 	try {
	 		$db=DBService::getDbById('note', $noteId);
	 		$collectionName = DBService::getCollectionNameById('note', $noteId);
	 		$result=$db->command(array('findAndModify'=>$collectionName,
	 				'query'=>array('_id'=>$noteId),
	 				'update'=>array('$inc'=>array('favNum'=>$num)),
	 				'new'=>true,
	 				'fields'=>array('favNum'=>1),
	 				'upsert'=>true
	 				));
	 		
	 		if($result==null || $result['ok']!=1)
	 			return Constants::$NUM_DB_ERROR;
	 		return $result['value']['favNum'];
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "NoteDao.updateFavoriteNum error, reason=".$e);
	 		return Constants::$NUM_DB_ERROR;
	 	}
	 }
	 
	 
	 private function getCollection($noteId) {
	 	$db=DBService::getDbById('note', $noteId);
	 	$collectionName = DBService::getCollectionNameById('note', $noteId);
	 	return $db->$collectionName;
	 }
	 
}